package cn.xyt.dto;

import java.nio.ByteOrder;

import cn.tom.kit.IoBuffer;

/**
 * 	消息ID msgid	 1
	消息体长度 length	2
	消息流水号 serial	2
	识别码 msgkey	12
	设备ID deviceid	4
	供应商代码supply	1
 */
public class Header {   //18 2b 7d f9
	private byte msgid; 
	
	private short length;
	
	private short serial;
	
	private String msgkey ="000000000000"; // 只有12个字节
	
	private int deviceid;
	
	private byte supply = 1;
	
	public byte getMsgid() {
		return msgid;
	}

	public void setMsgid(byte msgid) {
		this.msgid = msgid;
	}

	public short getLength() {
		return length;
	}

	public void setLength(short length) {
		this.length = length;
	}

	public short getSerial() {
		return serial;
	}

	public void setSerial(short serial) {
		this.serial = serial;
	}

	public byte getSupply() {
		return supply;
	}

	public void setSupply(byte supply) {
		this.supply = supply;
	}

	public String getMsgkey() {
		return msgkey;
	}

	public void setMsgkey(String msgkey) {
		if(msgkey.getBytes().length > 12){  // 按理其他都要判断, 但是因为都是获取回来的, 暂不判断
			throw new RuntimeException("msgid 识别码不能大于12个字节");
		}
		this.msgkey = msgkey;
	}

	public int getDeviceid() {
		return deviceid;
	}

	public void setDeviceid(int deviceid) {
		this.deviceid = deviceid;
	}
	
	public String getWebEntrityKey(){
		return ""+(getDeviceid()+this.serial);
	}

	@Override
	public String toString() {
		int msgid = (byte)getMsgid() & 0xFF;
		return "msgid=" +Integer.toHexString(msgid)+ ", length=" + length + ", deviceid=" + deviceid+", supply="+supply ;
	}

	public byte[] toByteBuf() {
		IoBuffer buf = IoBuffer.allocate(22);
		buf.buf().order(ByteOrder.LITTLE_ENDIAN);
		buf.writeByte(this.getMsgid());
		buf.writeShort(this.getLength());
		buf.writeShort(this.getSerial());
		buf.writeBytes(this.getMsgkey().getBytes());
		buf.writeInt(this.getDeviceid());
		buf.writeByte(this.getSupply());
		// 通用转义
		return buf.array() ;
	}
	
	
}
